#include "Tlc5940.h"
//#include "tlc_fades.h"
#include "ClickButton.h"

// the LED
int ledState = 0;

// the Button
const int buttonPin1 = 4;
ClickButton button1(buttonPin1, LOW, CLICKBTN_PULLUP);
TLC_CHANNEL_TYPE channel;

// Fade variables
int fadeValue = 64;
boolean fadeUp = false;    // false means fade down
boolean oldFadeUp = fadeUp;
const long fadeDelay = 10; // Time in milliseconds between fade steps
long adjustFaderTime = 0;  // Time to adjust the fader

// other
long currentTime;
int function = 0;


void setup()
{
  Tlc.init();
  Serial.begin(9600);
}

void loop()
{
  currentTime = (long)millis();

  button1.Update();

  if (button1.clicks != 0) function = button1.clicks;
  
  // Toggle LED on single clicks
  if(button1.clicks == 1) ledState = !ledState;

  // fade if button is held down during single-click
  if(function == -1 && button1.depressed == true)
  {
    ledState = true;  // force lights on, since we want to fade it up or down
    
    if (oldFadeUp == fadeUp) fadeUp = !fadeUp; // Switch direction
    
    if ( currentTime - adjustFaderTime > fadeDelay)
    {
      adjustFaderTime = currentTime + fadeDelay;
      if (fadeUp) fadeValue=fadeValue+10; else fadeValue=fadeValue-10;

      // Some boundary checking
      // Using signed ints, we can check for below 0 and above 255 (byte limit)
      if (fadeValue > 4090) fadeValue = 4090;
      if (fadeValue < 0)   fadeValue = 0;
      
    }

  } else {
    // Save old fade direction for next time
    oldFadeUp = fadeUp;
    // Reset function
    function = 0;
  }
  

  // update the LED
  //if (ledState) analogWrite(ledPin,fadeValue); else analogWrite(ledPin, 0);
  Serial.print ("fadevalue = ");
  Serial.println (fadeValue);
  Serial.print ("ledstate = ");
  Serial.println (ledState);
  if (ledState) Tlc.set(2,fadeValue); else Tlc.set(2,0);
  Tlc.update();
}
